package com.jpcc.vw.onlineRadio.activity;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Popup;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.cns.android.authentication.AppTokenInfo;
import com.google.gson.Gson;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.db.DownloadTrackDbBean;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.CommonFavouritePaiedHistoryEntity;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.DeleteFileUtil;
import com.jpcc.vw.onlineRadio.utils.PreferenceUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.sql.SQLException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SettingRadioActivity extends com.jpcc.vw.onlineRadio.base.BaseActivity {

    @BindView(R.id.tv_show_url)
    TextView tv_show_url;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.imv_top_bottom_line)
    ImageView imv_top_bottom_line;
    //    com.jpcc.vw.personalcenter
    MaterialDialog dialog2;
    MaterialDialog dialog;
    private IRadio radioModel;
    private BroadcastReceiver receiver;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_settings;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        tv_show_url.setText(Constants.BASE_URL);
        tv_title.setText(getResources().getString(R.string.string_4));
        radioModel = new RadioImpl();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.jpcc.vw.SettingRadioActivity");
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    if (intent.getAction().equals("com.jpcc.vw.SettingRadioActivity")) {
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
                            if ("ClearData".equals(bundle.getString("action"))) {
                                clearImageDiskCache(SettingRadioActivity.this);
                                String dataPath = "/storage/emulated/0/Android/data/com.jpcc.vw.onlineRadio/cache/video-cache";
                                File pathFile = new File(dataPath);
                                if (pathFile.exists()) {
                                    DeleteFileUtil.deleteDirectory(dataPath);
                                }
//                                ToastUtils.show(bundle.getString("action"));
                            }
                            else if("ClearSearchHistory".equals(bundle.getString("action"))){
                                clearSearchHistory();
                            }
                        }
                    }
                }
            }
        };
        this.registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        this.unregisterReceiver(receiver);
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (dialog2 != null && dialog2.isShowing()) {
            dialog2.dismiss();
        }
    }

    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            } else {
                imv_top_bottom_line.setColorFilter(Color.parseColor(color));
            }
        } else {
            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
        }
    }

    @Override
    public void setupData() {
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ToastUtils.show(R.string.string_63);
        }
    };


    /**
     * 清除图片磁盘缓存
     */
    public void clearImageDiskCache(final Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(context).clearDiskCache();
                        handler.sendEmptyMessage(0x02);
                    }
                }).start();
            } else {
                Glide.get(context).clearDiskCache();
                handler.sendEmptyMessage(0x02);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private CommonFavouritePaiedHistoryEntity DownloadTrackDbBean2CommonFavouritePaiedHistoryEntity(DownloadTrackDbBean source) {
        CommonFavouritePaiedHistoryEntity entity = new CommonFavouritePaiedHistoryEntity();
        entity.setId(source.getAlbumId());
        entity.setName(source.getAlbumName());
        entity.setHostName(source.getAuthor());
        entity.setCoverUrlSmall(source.getCover());
        entity.setCoverUrlMiddle(source.getCover());
        entity.setCoverUrlLarge(source.getCover());
        entity.setContentAbstract(source.getAlbumIntro());
//        entity.setCpSource(source.get);
        entity.setFrom(1);
        entity.setType("album");
        return entity;
    }

    private void clearSearchHistory() {

        radioModel.ClearSearchHistory().subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                DeleteBuilder deleteBuilder = null;
                try {
                    deleteBuilder = DatabaseHelperOrm.getHelper(SettingRadioActivity.this).getSearchHistoryDao().deleteBuilder();
                    deleteBuilder.where().eq("userId", MusicApplication.GetUserId());
                    deleteBuilder.delete();
                    ToastUtils.show(R.string.string_64);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.show(response.getStatusMessage());
            }
        });
    }

    @OnClick({R.id.layout_purchase, R.id.layout_account, R.id.layout_back, R.id.layout_clear_media_data, R.id.imv_new_search, R.id.layout_base_url, R.id.layout_vip})
    void doClicks(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.layout_purchase:
                if(!Constants.isRelease){
                    dialog2 = new MaterialDialog.Builder(this).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_67)).positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            clearSearchHistory();
                        }
                    }).build();
                    dialog2.show();
                }
                else{
                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    Intent setAlertIntent = new Intent("com.jpcc.vw.SettingRadioActivity");
                    setAlertIntent.putExtra("action", "ClearSearchHistory");
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_67));
                    popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                    popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                    notificationManager.addPopup(0x0002, popup);
                }
                break;
            case R.id.layout_account:
                //com.jpcc.vw.personalcenter.
//                Intent intent_account = new Intent(this, PersonalInfoActivity.class);
//                startActivity(intent_account);
                try {
                    Intent intent = this.getPackageManager().getLaunchIntentForPackage("com.jpcc.vw.personalcenter");
                    intent.putExtra("mediaType", 1);
                    intent.putExtra("jumpType", 1);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } catch (Exception e) {
                    Toast.makeText(this, "Personal Center not installed", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.layout_back:
                this.finish();
                break;
            case R.id.layout_clear_media_data:
                if (!Constants.isRelease) {
                    dialog = new MaterialDialog.Builder(this).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_35)).positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            clearImageDiskCache(SettingRadioActivity.this);
                            String dataPath = "/storage/emulated/0/Android/data/com.jpcc.vw.onlineRadio/cache/video-cache";
                            File pathFile = new File(dataPath);
                            if (pathFile.exists()) {
                                DeleteFileUtil.deleteDirectory(dataPath);
                            }
                        }
                    }).build();
                    dialog.show();
                } else {
                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    Intent setAlertIntent = new Intent("com.jpcc.vw.SettingRadioActivity");
                    setAlertIntent.putExtra("action", "ClearData");
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_35));
                    popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                    popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                    notificationManager.addPopup(0x0001, popup);
                }
                break;
            case R.id.imv_new_search:
                Intent intent_search = new Intent(this, SearchActivity.class);
                startActivity(intent_search);
                break;
            case R.id.layout_base_url:
                if (Constants.BASE_URL.equals(Constants.BASE_URL_YIQI)) {
                    AppTokenInfo tokenInfo = new Gson().fromJson(PreferenceUtils.GetTokenInfo(), AppTokenInfo.class);
                    String url = "https://hu-api-uat.mos.csvw.com/mos/radio/api/v1/";
                    if (tokenInfo != null && !TextUtils.isEmpty(tokenInfo.getUrl())) {
                        url = tokenInfo.getUrl();
                    }
                    Constants.BASE_URL = url;
                } else {
                    Constants.BASE_URL = Constants.BASE_URL_YIQI;
                }
                tv_show_url.setText(Constants.BASE_URL);
                break;
            case R.id.layout_vip:
                try {
                    Intent intent = this.getPackageManager().getLaunchIntentForPackage("com.jpcc.vw.personalcenter");
                    intent.putExtra("mediaType", 1);
                    intent.putExtra("jumpType", 2);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } catch (Exception e) {
                    Toast.makeText(this, "Personal Center not installed", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
